import axios from 'axios'
import router from '../router'
import store from '../store'
import { Toast } from 'vant'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// 将一个对象转成QueryString
function urlencode(data) {
  var _result = []
  for (var key in data) {
    var value = data[key]
    _result.push(key + '=' + value)
  }
  return _result.join('&')
}

export function request(reqUrl, data = {}, type = 'POST', auth = 'member', headers = {}) {
  if (!reqUrl) {
    return
  }
  type = type.toUpperCase()
  reqUrl = process.env.VUE_APP_API_HOST + '/' + reqUrl

  data.client = 'wap'
  data.client_type = 'wap'

  if (auth === 'member') {
    headers['X-DS-KEY'] = store.state.user.token
  }

  let axiosData
  if (type === 'POST') {
    axiosData = {
      headers: {
        ...headers
        // client: 'H5' // 添加终端类型
      },
      method: type,
      url: reqUrl,
      data: data
    }
  } else {
    if (JSON.stringify(data) !== '{}') {
      reqUrl += '?' + urlencode(data)
    }
    axiosData = {
      headers: headers,
      method: type,
      url: reqUrl
    }
  }
  return new Promise((resolve, reject) => {
    axios(axiosData).then(
      res => {
        if (res.data.code === 10000 || res.data.code === '10000') {
          resolve(res.data)
        } else {
          if (res.data.code === 11001) {
            Toast.loading({
              message: res.data.message
            })
            store.commit('memberLogout')
            // 防止多个接口同时退出登录
            clearTimeout(window.toLoginTimeOut)
            window.toLoginTimeOut = setTimeout(() => {
              router.push({ name: 'HomeLogin' })
            }, 2000)
          }
          reject(res.data)
        }
      },
      error => {
        reject(error)
      }
    )
  })
}

// 不带提示和拦截的请求
// export function requestRaw (reqUrl, type = 'POST', data = {}) {
//   type = type.toUpperCase()
//   let axiosData
//   if (type === 'POST') {
//     axiosData = {
//       method: type,
//       url: reqUrl,
//       data: data
//     }
//   } else {
//     if (JSON.stringify(data) !== '{}') {
//       reqUrl += '?' + urlencode(data)
//     }
//     axiosData = {
//       method: type,
//       url: reqUrl
//     }
//   }
//   return new Promise((resolve, reject) => {
//     axios(axiosData).then(
//       res => {
//         resolve(res.data)
//       },
//       error => {
//         reject(error)
//       }
//     )
//   })
// }
